package com.wlstock.funi.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.wlstock.funi.constant.URLConstant;
import com.wlstock.funi.dao.FundStaticModelDao;
import com.wlstock.funi.model.FundStaticModel;
import com.wlstock.funi.request.CustomStringRequest;
import com.wlstock.funi.request.EventBusConstants;
import com.wlstock.funi.request.NetWorkListener;
import com.wlstock.funi.utils.CaculateUtils;
import com.wlstock.funi.utils.StrUtils;

import de.greenrobot.event.EventBus;

/**
 * 
 * @author admin
 *	查询万隆上所有操盘手的历史操作记录
 */
public class QueryHisService extends Service implements NetWorkListener {
	private Stack<String> stack;
	private String currentSeason;
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		EventBus.getDefault().register(this);
		
	}
	
	@Override
	public void onStart(Intent intent, int startId) {
		try {
			stack = CaculateUtils.getSeasons(new Date(),new SimpleDateFormat("yyyy-MM-dd").parse("2012-08-01"));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		queryLastHisInStack(true);
		
	}

	private void queryLastHisInStack(boolean isLoadSuccess) {
		if (stack==null || stack.empty()) {
			return;
		}
		if (isLoadSuccess) {
			currentSeason = stack.peek();
			stack.pop();
		}
		List<FundStaticModel> curSeasonFundModels = FundStaticModelDao.getInstance(this).querFundStaticModelsBySeanson(currentSeason);
		if (curSeasonFundModels!=null && curSeasonFundModels.size() == 0) {
			HashMap<String, String> parms = new HashMap<String, String>();
			parms.put("season", currentSeason);
			CustomStringRequest curRequest = new CustomStringRequest();
			curRequest.networkResponseListener = this;
			curRequest.requestGet(URLConstant.WLHOST, URLConstant.WL_STATIC_FUND_PROFIT, null, parms);
		} else {
			Toast.makeText(this,"数据库中第" +currentSeason + "期已经存在", 500).show();
		}
		
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
	}
	
	@Override
	public void onErrorResponse(VolleyError error, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onErrorResponse(VolleyError error, String eventCode) {
		// TODO Auto-generated method stub
		if (URLConstant.WL_STATIC_FUND_PROFIT.equals(eventCode)){
			//出错继续加载当前的那一期
			queryLastHisInStack(false);
		}
	}

	@Override
	public void onResponse(String response, EventBusConstants eventCode) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onResponse(String response, String eventCode) {
		// TODO Auto-generated method stub
		if (URLConstant.WL_STATIC_FUND_PROFIT.equals(eventCode)) {
			String str = StrUtils.parseResponse(response);
			JSONObject object ;
			try {
				object = new JSONObject(str);
				JSONArray datas = object.getJSONArray("Data");
				for (int i = 0; i < datas.length(); i++) {
					JSONObject oneObj = (JSONObject) datas.get(i);
					Log.e("TAG", datas.get(i).toString());
					JSONArray staticsArrs = oneObj.getJSONArray("StatisticsStockList");
					for (int j = 0; j < staticsArrs.length(); j++) {
						FundStaticModel staticModel = new FundStaticModel();
						String currentYear = CaculateUtils.getSeasonDate(currentSeason);
						staticModel.setSeason(Integer.valueOf(currentSeason));
						staticModel.setFundId(oneObj.optInt("FundId"));
						staticModel.setFundName(oneObj.optString("FundName"));
						staticModel.setSumProfitPreCent((float)oneObj.optDouble("SumProfitPreCent"));
						staticModel.setTradeCount(oneObj.optInt("TradeCount"));
						JSONObject staticsObj = staticsArrs.getJSONObject(j);
						String endDate = staticsObj.optString("EndDate");
						String startDate = staticsObj.optString("StartDate");
						staticsObj.put("EndDate", currentYear+endDate);
						staticsObj.put("StartDate", currentYear+startDate);
						staticModel.setOneTradeInfo(staticsObj);
						FundStaticModelDao.getInstance(this).addFundStaticModel(staticModel);
					}
				}
				Toast.makeText(this,"第" +currentSeason + "期加载成功", 500).show();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this,"第" +currentSeason + "期加载失败", 500).show();
				e.printStackTrace();
				return;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				Toast.makeText(this,"第" +currentSeason + "期加载失败", 500).show();
				e.printStackTrace();
			}
			new Handler().postDelayed(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					queryLastHisInStack(true);
				}
			}, 1000);
		} 
	}
	

}
